package com.qf.nio.selector;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description:
 * @Author: xbb
 * @Date:2020/4/20
 */
public class ServerDemo {
    public static void main(String[] args) throws Exception{
        //1.创建服务器
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);

        //2.绑定端口
        serverSocketChannel.bind(new InetSocketAddress(8080));

        //3.创建多路复用器
        Selector selector = Selector.open();

        //4.把ServerSocketChannel绑定到多路复用器
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //5.如果select()大于0说明多路复用器中有要处理的请求
        while (selector.select()>0){
            //6.获取多路复用器中待处理的请求
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            for (SelectionKey sk:new HashSet<>(selectionKeys)){

                selectionKeys.remove(sk);   //处理完请求删除

                //7.判断请求的事件类型
                if(sk.isAcceptable()){  //代表的是新的连接
                    //8.转成ServerSocketChannel
                    ServerSocketChannel  ssc  = (ServerSocketChannel) sk.channel();

                    //9.获取新客户端
                    SocketChannel socketChannel = ssc.accept();

                    //10.设置新的客户端非阻塞
                    socketChannel.configureBlocking(false);

                    //11.把新的客户端绑定到多路复用器上面
                    socketChannel.register(selector,SelectionKey.OP_READ);

                } else if(sk.isReadable()){ //代表的是读取的消息类型
                    //1.转成SocketChannel
                    SocketChannel socketChannel = (SocketChannel) sk.channel();

                    //2.创建ByteBuffer
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024*10);
                    socketChannel.read(byteBuffer);

                    System.out.println("服务端读取的内容："+new String(byteBuffer.array(),"utf-8"));
                }
            }
        }
    }
}
